package com.azunitech.jms.biz;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import com.azunitech.jms.common.ILifeControl;

public class ServiceManager<T extends ILifeControl> {
	private List<ILifeControl> m_Services;
	@Inject BeanManager m_BeanManager;
	
	@SuppressWarnings("unchecked")
	private <T> List<T> lookupList(final Class<T> clazz) {
	    List<T> results = new ArrayList<T>();
	    Iterator<Bean<?>> iter = m_BeanManager.getBeans(clazz).iterator();
	    if (!iter.hasNext()) {
	        throw new IllegalStateException("CDI BeanManager cannot find an instance of requested type " + clazz.getName());
	    }
	    
	    while( iter.hasNext()){
		    Bean<T> bean = (Bean<T>) iter.next();
		    CreationalContext<T> ctx = m_BeanManager.createCreationalContext(bean);
		    T t = (T) m_BeanManager.getReference(bean, clazz, ctx);
		    results.add(t);
	    }
	    return results;
   	}
	
	public void init(){
		this.m_Services = new ArrayList<ILifeControl>();

		List<T> serviceList = (List<T>) this.lookupList(ILifeControl.class);
		for( ILifeControl service : serviceList){
			service.init();
			this.m_Services.add(service);
		}
	}
}
